package com.xxkj.drugtraceability.ui.login

import android.app.Application
import android.content.Context
import android.content.Intent
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.xxhis.drugtraceability.base.BaseViewModel
import com.xxkj.drugtraceability.App
import com.xxkj.drugtraceability.base.Constants
import com.xxkj.drugtraceability.bean.LoginRequest
import com.xxkj.drugtraceability.bean.LoginUiState
import com.xxkj.drugtraceability.bean.PdaEquipmentApiDto
import com.xxkj.drugtraceability.ext.putSpValue
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import com.xxkj.drugtraceability.net.Result
import com.xxkj.drugtraceability.net.WanService
import com.xxkj.drugtraceability.net.WanService.Companion.BASE_URL_API
import com.xxkj.drugtraceability.ui.main.MainActivity
import com.xxkj.drugtraceability.utils.CommonUtils.getDeviceUUid

/**
 * author: zhoujingjin
 * created on: 2024/9/9 16:53
 * description:
 */
class LoginViewModel(application: Application, private var loginRepository: LoginRepository):BaseViewModel(application) {
    var imageBase64 = MutableLiveData<String?>()
    private var _uiState = MutableLiveData<LoginUiState<String>>(LoginUiState())
    var eyeType = MutableLiveData<Boolean>(false)
    val uiState: LiveData<LoginUiState<String>>
        get() = _uiState
    var uuid = ""
    fun getCode(){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                val codeResult = loginRepository.getCode()
                if (codeResult is Result.Success){
                    imageBase64.postValue(codeResult.data.img)
                    uuid = codeResult.data.uuid
                }else if (codeResult is Result.Error){
                    _uiState.postValue(LoginUiState(isError = codeResult.errorData))
                }
            }}
    }

    fun changePass() {
        eyeType.postValue(!eyeType.value!!)
    }
    fun login(loginRequest: LoginRequest,context: Context){
        viewModelScope.launch(Dispatchers.Main) {
            withContext(Dispatchers.IO) {
                _uiState.postValue(LoginUiState(isLoading = true))
                val loginResult = loginRepository.login(Gson().toJson( loginRequest))
                if (loginResult is Result.Success){
                    app.putSpValue(Constants.TOKEN,loginResult.data.data.token)
                    App.token = loginResult.data.data.token
                    //拿token去获取用户信息
                    val userResult = loginRepository.getUserInfo()
                    if (userResult is Result.Success){
                        //拿到用户信息,验证设备,切换地址，用的两套地址，登录一套，业务一套
                        try {
                            val result =  loginRepository.checkEquipment(Gson().toJson(PdaEquipmentApiDto(applyDeptId = userResult.data.data.user.deptCode
                                  ,applyUserName = userResult.data.data.user.userName,
                              applyUserId = userResult.data.data.user.userId,macId = getDeviceUUid(context),model = android.os.Build.MODEL)))
                            if (userResult.data.data.user.deptCode == null) {
                                app.putSpValue("deptId", "")
                                app.putSpValue("deptName", "")
                            } else {
                                app.putSpValue("deptId", userResult.data.data.user.deptCode)
                                app.putSpValue("deptName", userResult.data.data.user.deptCode)
                            }
                            if (result is Result.Success){
                                //去到首页
                                context.startActivity(Intent(context,MainActivity::class.java))
                                context as LoginActivity
                                context.finish()
                            }else if (result is Result.Error){
                                //提示信息
                                App.token = ""
                                _uiState.postValue(LoginUiState(isLoading = false,isError = result.errorData?:result.exception.cause?.message))
                            }
                        } catch (e: Exception) {
                            _uiState.postValue(LoginUiState(isLoading = false,isError = e.message))
                        }
                    }else if (userResult is Result.Error){
                        App.token =""
                        _uiState.postValue(LoginUiState(isLoading = false,isError = userResult.errorData?:userResult.exception.cause?.message))
                    }
                }else if (loginResult is Result.Error){
                    if (loginResult.code==500){
                        getCode()
                    }
                    _uiState.postValue(LoginUiState(isError = loginResult.errorData?:loginResult.exception.cause?.message))
                }
            }}
    }
}